package com.gzcss.gulimall.product.service.impl;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.alibaba.fastjson2.TypeReference;
import com.gzcss.common.constant.ProductConstant;
import com.gzcss.common.to.SkuReductionTo;
import com.gzcss.common.to.SpuBoundsTo;
import com.gzcss.common.to.WareTo.SkuHasStock;
import com.gzcss.common.to.elasticsearch.SkuEsModel;
import com.gzcss.common.utils.R;
import com.gzcss.gulimall.product.entity.*;
import com.gzcss.gulimall.product.feign.CouponFeignService;
import com.gzcss.gulimall.product.feign.SearchFeignService;
import com.gzcss.gulimall.product.feign.WareFeignService;
import com.gzcss.gulimall.product.service.*;
import com.gzcss.gulimall.product.vo.savaVo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gzcss.common.utils.PageUtils;
import com.gzcss.common.utils.Query;

import com.gzcss.gulimall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    private SpuInfoDescService spuInfoDescService;

    @Autowired
    private SpuImagesService spuImagesService;

    @Autowired
    private AttrService attrService;

    @Autowired
    private SkuSaleAttrValueService saleAttrValueService;

    @Autowired
    private ProductAttrValueService valueService;

    @Autowired
    private SkuInfoService skuInfoService;

    @Autowired
    private SkuImagesService skuImagesService;

    @Autowired
    CouponFeignService couponFeignService;

    @Autowired
    BrandService brandService;

    @Autowired
    CategoryService categoryService;

    @Autowired
    WareFeignService wareFeignService;

    @Autowired
    SearchFeignService searchFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVo vo) {
        //1、保存spu基本信息 pms_spu_info
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(vo,spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        this.saveBeanSpuInfo(spuInfoEntity);
        //2、保存Spu的描述图片 pms_spu_info_desc
        List<String> decript = vo.getDecript();
        SpuInfoDescEntity spuInfoDesc = new SpuInfoDescEntity();
        spuInfoDesc.setSpuId(spuInfoEntity.getId());
        spuInfoDesc.setDecript(String.join(",",decript));
        spuInfoDescService.saveSputInfoDesc(spuInfoDesc);

        //3、保存spu的图片集 pms_spu_images
        List<String> images = vo.getImages();
        spuImagesService.saveImage(spuInfoEntity.getId(),images);

        //4、保存spu的规格参数;pms_product_attr_value
        List<BaseAttrs> baseAttrs = vo.getBaseAttrs();
        List<ProductAttrValueEntity> collect = baseAttrs.stream().map(attr -> {
            ProductAttrValueEntity valueEntity = new ProductAttrValueEntity();
            valueEntity.setAttrId(attr.getAttrId());
            AttrEntity byId = attrService.getById(attr.getAttrId());
            valueEntity.setAttrName(byId.getAttrName());
            valueEntity.setAttrValue(attr.getAttrValues());
            valueEntity.setQuickShow(attr.getShowDesc());
            valueEntity.setSpuId(spuInfoEntity.getId());

            return valueEntity;
        }).collect(Collectors.toList());
        valueService.saveProductAttr(collect);


        //5、保存spu的积分信息；gulimall_sms->sms_spu_bounds
        Bounds bounds = vo.getBounds();
        SpuBoundsTo spuBoundsTo = new SpuBoundsTo();
        BeanUtils.copyProperties(bounds,spuBoundsTo);
        spuBoundsTo.setSpuId(spuInfoEntity.getId());
        R r = couponFeignService.saveSpuBounds(spuBoundsTo);
        if(r.getCode() != 0){
            log.error("远程保存spu积分信息失败");
        }


        //5、保存当前spu对应的所有sku信息；
        List<Skus> skus = vo.getSkus();
        skus.forEach(item->{
            String defaultImge = "";
            for (Images image:item.getImages()) {
                if(image.getDefaultImg() == 1){
                    defaultImge = image.getImgUrl();
                }
            }

            SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
            BeanUtils.copyProperties(item,skuInfoEntity);
            skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
            skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
            skuInfoEntity.setSaleCount(0L);
            skuInfoEntity.setSpuId(spuInfoEntity.getId());
            skuInfoEntity.setSkuDefaultImg(defaultImge);
            //5.1）、sku的基本信息；pms_sku_info
            skuInfoService.saveSkuInfo(skuInfoEntity);

            //保存后，获取skuId
            Long skuId = skuInfoEntity.getSkuId();
            //5.2）、保存sku的图片信息；pms_sku_image
            List<SkuImagesEntity> imagesEntity = item.getImages().stream().map(img -> {
                SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                skuImagesEntity.setSkuId(skuId);
                skuImagesEntity.setImgUrl(img.getImgUrl());
                skuImagesEntity.setDefaultImg(img.getDefaultImg());
                return skuImagesEntity;
            }).filter(entity->{
                //返回true就是需要，返回flase就剔除
                return !StringUtils.isEmpty(entity.getImgUrl());
            }).collect(Collectors.toList());
            //TODO 没有图片路径的，无需保存
            skuImagesService.saveBatch(imagesEntity);

            //5.3）、sku的销售属性信息：pms_sku_sale_attr_value
            List<Attr> attr = item.getAttr();
            List<SkuSaleAttrValueEntity> saleAttrValueEntities = attr.stream().map(a -> {
                SkuSaleAttrValueEntity saleAttrValueEntity = new SkuSaleAttrValueEntity();
                BeanUtils.copyProperties(a, saleAttrValueEntity);
                saleAttrValueEntity.setSkuId(skuId);

                return saleAttrValueEntity;
            }).collect(Collectors.toList());
            saleAttrValueService.saveBatch(saleAttrValueEntities);

            // /5.4）、sku的优惠、满减等信息；gulimall_sms->sms_sku_ladder\sms_sku_full_reduction\sms_member_price
            SkuReductionTo skuReductionTo = new SkuReductionTo();
            BeanUtils.copyProperties(item,skuReductionTo);
            skuReductionTo.setMemberPrice(item.getMemberPrice());
            skuReductionTo.setSkuId(skuId);
            if(skuReductionTo.getFullCount() > 0 || skuReductionTo.getFullPrice().compareTo(new BigDecimal("0")) == 1){
                R r1 = couponFeignService.savaInfo(skuReductionTo);
                if(r1.getCode() != 0){
                    log.error("远程保存sku优惠信息失败");
                }
            }
        });
    }

    @Override
    public void saveBeanSpuInfo(SpuInfoEntity spuInfoEntity) {
        this.baseMapper.insert(spuInfoEntity);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if(!StringUtils.isEmpty(key)){
            wrapper.and((w)->{
                w.eq("id",key).or().like("spu_name",key);
            });
        }
        String status = (String) params.get("status");
        if(!StringUtils.isEmpty(status) ){
            wrapper.eq("publish_status",status);
        }
        String brandId = (String) params.get("brandId");
        if(!StringUtils.isEmpty(brandId) && !"0".equalsIgnoreCase(brandId)){
            wrapper.eq("brand_id",brandId);
        }
        String catelogId = (String) params.get("catelogId");
        if(!StringUtils.isEmpty(catelogId) && !"0".equalsIgnoreCase(catelogId)){
            wrapper.eq("catalog_id",catelogId);
        }


        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public void spuup(Long spuId) {
        //组装需要上架的数据

        //查出相应spuid对应的所有sku信息、品牌名
        List<SkuInfoEntity> skulist = skuInfoService.getSkuBySpuId(spuId);
        List<Long> skuIDlist = skulist.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());

        //TODO 4 查询SKU所有可以被用来检索的属性
        //1、根据spu查询ProductAttrValueService中所有对应attr的attrID
        List<ProductAttrValueEntity> baseAttrs = valueService.baseAttrforSpu(spuId);
        //2、查出所有spu对应的attrID
        List<Long> attrids = baseAttrs.stream().map(item -> {
            return item.getAttrId();
        }).collect(Collectors.toList());
        //3、根据attrID 查询attr里所有可以用来被检索的数据(search_type）
        List<Long> Searchids = attrService.selectSearchAttrids(attrids);

        //将数组转为set集合
        //Set idSet = new HashSet(Searchids);
        Set idSet = Searchids.stream().collect(Collectors.toSet());

        //TODO 1'向库存系统发送请求获取商品库存状态(不需要查询具体的库存数量，只需要查询是否有库存即可)
        //发送远程调用ware系统查库存
        Map<Long, Boolean> hosStockMap = null;
        try{
            R<List<SkuHasStock>> hosStockList = wareFeignService.hasStock(skuIDlist);
            TypeReference<List<SkuHasStock>> typeReference = new TypeReference<List<SkuHasStock>>() {
            };
            hosStockMap = hosStockList.getData(typeReference).stream().collect(Collectors.toMap(SkuHasStock::getSkuId, item -> item.isHasStock()));
        }catch (Exception e){
            log.error("远程调用ware服务异常：原因{}",e);
        }
        Map<Long, Boolean> finalHosStockMap = hosStockMap;

        List<SkuEsModel.Attrs> attrs = baseAttrs.stream().map(item -> {
            return idSet.contains(item.getAttrId());
        }).map(item -> {
            SkuEsModel.Attrs attrs1 = new SkuEsModel.Attrs();
            BeanUtils.copyProperties(item, attrs1);
            return attrs1;
        }).collect(Collectors.toList());

        //封装每个SKU的信息
        List<SkuEsModel> upProduct = skulist.stream().map(sku -> {
            SkuEsModel skuEsModel = new SkuEsModel();
            //属性对拷
            BeanUtils.copyProperties(sku,skuEsModel);
            //处理skuentity中和skuesmodel有出入的属性
            skuEsModel.setSkuPrice(sku.getPrice());
            skuEsModel.setSkuImg(sku.getSkuDefaultImg());

            //hasStock商品库存，hotscore 商品热度
            //商品库存
            if(finalHosStockMap == null){
                skuEsModel.setHasStock(true);
            }else{
                skuEsModel.setHasStock(finalHosStockMap.get(sku.getSkuId()));
            }

            //TODO 2 商品热度
            skuEsModel.setHotScore(0L);

            //TODO 3 查询品牌和分类信息
            //brandName 品牌名 brandImg 品牌图片
            BrandEntity brand = brandService.getById(sku.getBrandId());
            skuEsModel.setBrandName(brand.getName());
            skuEsModel.setBrandImg(brand.getLogo());
            // catalogName 分类信息
            CategoryEntity category = categoryService.getById(skuEsModel.getCatalogId());
            skuEsModel.setCatalogName(category.getName());

            skuEsModel.setAttrs(attrs);

            return skuEsModel;
        }).collect(Collectors.toList());

        //TODO 5 将数据发送到esaticsearch保存：gulimall-search
        try {
            R r = searchFeignService.productStatusUp(upProduct);
            if(r.getCode() == 0){
                //远程调用成功
                //TODO 6 修改当前SPU的状态
                baseMapper.updateSpuSatus(spuId, ProductConstant.SatusEnum.SPU_UP.getCode());
            }else{
                //远程调用失败
                //TODE 7 重复调用问题？接口幂等性

            }
        }catch (Exception e){
            log.error("远程保存elasticsearch异常：原因{}",e);
        }



    }


}
